package lipengfei.botaiframework.security.jwt.handler.impl;
import cn.hutool.core.map.MapUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;

import lipengfei.botaiframework.jwt.JwtConst;
import lipengfei.botaiframework.jwt.JwtProperties;
import lipengfei.botaiframework.jwt.JwtUtil;
import lipengfei.botaiframework.security.jwt.filter.JwtTokenFilter;
import lipengfei.botaiframework.security.jwt.handler.TokenRefreshHandler;

import lipengfei.botaiframework.security.jwt.properties.JwtRefreshTokenProperties;
import lipengfei.botaiframework.security.jwt.properties.JwtTokenProperties;
import lipengfei.botaiframework.utils.http.ResponseUtil;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

/**
 * token过期但是refreshToken还未过期的情况,
 * 需要同时刷新token和refreshToken
 * */
public class RefreshTokenHandler implements lipengfei.botaiframework.security.jwt.handler.TokenRefreshHandler {


    public void handle(HttpServletRequest request, HttpServletResponse response) {

        String jwtRefreshTokenOld = request.getHeader(JwtRefreshTokenProperties.headerName);
        String tokenOld = JwtUtil.getClaim(jwtRefreshTokenOld,JwtConst.ACCOUNT);
        String account=  JwtUtil.getClaim(tokenOld,JwtConst.ACCOUNT);


        JwtProperties jwtProperties = JwtTokenProperties.buildJwtProperties();
        String token = JwtUtil.generateToken(jwtProperties, account, new Date());

        JwtProperties jwtRefreshProperties = JwtRefreshTokenProperties.buildJwtProperties();
        String refreshToken = JwtUtil.generateToken(jwtRefreshProperties, token, new Date());


        Map<Object, Object> tokenMap = MapUtil.of(new String[][] {
                {"accessToken", token},
                {"refreshAccessToken", refreshToken}
        });

        response.setHeader(JwtTokenProperties.headerName, token);
        response.setHeader(JwtRefreshTokenProperties.headerName, refreshToken);

    }
}